package com.basin.feign.interceptor;

import com.basin.common.core.exception.BasinException;
import com.basin.feign.config.Init4FeignLogic;
import com.basin.feign.config.vo.FeignReqSettingsVO;
import com.basin.feign.util.SignUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @author: Sam ZHONG | sammy1997@aliyun.com
 */
@Slf4j
public class FeignRequestInterceptor implements RequestInterceptor {
    @Resource
    private Init4FeignLogic feignLogic;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 获取访问的服务的应用名
        String applicationName = requestTemplate.feignTarget().name();
        Map<String, FeignReqSettingsVO> settingsMap = this.feignLogic.collectFeignReqSettings();
        FeignReqSettingsVO vo = settingsMap.get(applicationName);
        if (vo == null) {
            throw new BasinException("Feign请求代理创建失败：未读取到应用[" + applicationName + "]对应的配置项");
        }
        String authToken = SignUtil.createSignature(vo);
        // 加入请求头
        requestTemplate.header("Authorization", authToken);
    }

}
